class EventsController < ApplicationController
  def list

    if (params[:sort_by] != nil)
      if (params[:filter] != nil and params[:filter][:type] != "")
        if params[:filter][:type] == "Dues"
          @events = Event.find(:all, :select => "events.*", :conditions => ["(events.event_type = \"Dues\" OR events.event_type = \"Dues (late)\") AND events.date >= CURRENT_TIMESTAMP AND events.deleted = 0 AND events.semester_index = #{Event.getCurrentSemester}"], :order => "#{params[:sort_by]} ASC")
        else
          @events = Event.find(:all, :select => "events.*", :conditions => ["events.event_type = \"#{params[:filter][:type]}\" AND events.date >= CURRENT_TIMESTAMP AND events.deleted = 0 AND events.semester_index = #{Event.getCurrentSemester}"], :order => "#{params[:sort_by]} ASC")
        end
      else
        @events = Event.find(:all, :select => "events.*", :conditions => ["events.event_type != \"Indy Hours\" AND events.deleted = 0 AND events.date >= CURRENT_TIMESTAMP AND events.semester_index = #{Event.getCurrentSemester}"], :order => "#{params[:sort_by]} ASC")
      end
    else
      if (params[:filter] != nil and params[:filter][:type] != "")
        if params[:filter][:type] == "Dues"
          @events = Event.find(:all, :select => "events.*", :conditions => ["(events.event_type = \"Dues\" OR events.event_type = \"Dues (late)\") AND events.date >= CURRENT_TIMESTAMP AND events.deleted = 0 AND events.semester_index = #{Event.getCurrentSemester}"], :order => "date ASC")
        else
          @events = Event.find(:all, :select => "events.*", :conditions => ["events.deleted = 0 AND events.date >= CURRENT_TIMESTAMP AND events.event_type = \"#{params[:filter][:type]}\" AND events.semester_index = #{Event.getCurrentSemester}"], :order => "date ASC")
        end
      else
        @events = Event.find(:all, :select => "events.*", :conditions => ["events.event_type != \"Indy Hours\" AND events.deleted = 0 AND events.date >= CURRENT_TIMESTAMP AND events.semester_index = #{Event.getCurrentSemester}"], :order => "date ASC")
      end
    end

  end


  def old_list

    if (params[:sort_by] != nil)
      if (params[:filter] != nil and params[:filter][:type] != "")
        if params[:filter] == "Dues"
          @events = Event.find(:all, :select => "events.*", :conditions => ["(events.event_type = \"Dues\" OR events.event_type = \"Dues (late)\") AND events.date < CURRENT_TIMESTAMP AND events.deleted = 0 AND events.semester_index = #{Event.getCurrentSemester}"], :order => "#{params[:sort_by]} DESC")
        else
          @events = Event.find(:all, :select => "events.*", :conditions => ["events.event_type = \"#{params[:filter][:type]}\" AND events.date < CURRENT_TIMESTAMP AND events.deleted = 0 AND events.semester_index = #{Event.getCurrentSemester}"], :order => "#{params[:sort_by]} DESC")
        end
      else
        @events = Event.find(:all, :select => "events.*", :conditions => ["events.deleted = 0 AND events.date < CURRENT_TIMESTAMP AND events.semester_index = #{Event.getCurrentSemester}"], :order => "#{params[:sort_by]} DESC")
      end
    else
      if (params[:filter] != nil and params[:filter][:type] != "")
        if params[:filter] == "Dues"
          @events = Event.find(:all, :select => "events.*", :conditions => ["events.deleted = 0 AND events.date < CURRENT_TIMESTAMP AND (events.event_type = \"Dues\" OR events.event_type = \"Dues (late)\") AND events.semester_index = #{Event.getCurrentSemester}"], :order => "date DESC")
        else
          @events = Event.find(:all, :select => "events.*", :conditions => ["events.deleted = 0 AND events.date < CURRENT_TIMESTAMP AND events.event_type = \"#{params[:filter][:type]}\" AND events.semester_index = #{Event.getCurrentSemester}"], :order => "date DESC")
        end
      else
        @events = Event.find(:all, :select => "events.*", :conditions => ["events.deleted = 0 AND events.date < CURRENT_TIMESTAMP AND events.semester_index = #{Event.getCurrentSemester}"], :order => "date DESC")
      end
    end

  end


  def old_semester_list

    if (params[:sort_by] != nil)
      if (params[:filter] != nil and params[:filter][:type] != "")
        if params[:filter] == "Dues"
          @events = Event.find(:all, :select => "events.*", :conditions => ["(events.event_type = \"Dues\" OR events.event_type = \"Dues (late)\") AND events.deleted = 0 AND events.semester_index < #{Event.getCurrentSemester}"], :order => "#{params[:sort_by]} DESC")
        else
          @events = Event.find(:all, :select => "events.*", :conditions => ["events.event_type = \"#{params[:filter][:type]}\" AND events.deleted = 0 AND events.semester_index < #{Event.getCurrentSemester}"], :order => "#{params[:sort_by]} DESC")
        end
      else
        @events = Event.find(:all, :select => "events.*", :conditions => ["events.deleted = 0 AND events.semester_index < #{Event.getCurrentSemester}"], :order => "#{params[:sort_by]} DESC")
      end
    else
      if (params[:filter] != nil and params[:filter][:type] != "")
        if params[:filter] == "Dues"
          @events = Event.find(:all, :select => "events.*", :conditions => ["events.deleted = 0 AND (events.event_type = \"Dues\" OR events.event_type = \"Dues (late)\") AND events.semester_index < #{Event.getCurrentSemester}"], :order => "date DESC")
        else
          @events = Event.find(:all, :select => "events.*", :conditions => ["events.deleted = 0 AND events.event_type = \"#{params[:filter][:type]}\" AND events.semester_index < #{Event.getCurrentSemester}"], :order => "date DESC")
        end
      else
        @events = Event.find(:all, :select => "events.*", :conditions => ["events.deleted = 0 AND events.semester_index < #{Event.getCurrentSemester}"], :order => "date DESC")
      end
    end

  end


  def deleted
    @events = Event.find(:all, :conditions => {:deleted => true}, :order => "date ASC")
  end


  def undelete
    @event = Event.find(params[:event_id])

    AttendanceRecord.find(:all, :conditions => {:event_id => @event}).each do |record|
      record.deleted = false
      record.save
    end

    @event.deleted = false
    @event.save

    AttendanceRecord.find(:all, :select => "members.id", :conditions => ["attendance_records.event_id = #{@event.id}"], :include =>[:member]).each do |record|
      @member = Member.find(record.member.id)
      @member.up_to_date = false
      @member.save
    end

    redirect_to :action => "deleted"
  end


  def print
    @event = Event.find(params[:id])
  end


  def create
    @event = Event.new
    render :action => "edit"
  end

  def indy_hour_submission
    @event = Event.new
    render :action => "indy_hour_submission"
  end

  def save_indy_hours
    @event = Event.new

    @event.attributes = params[:event]
    @event.event_type = "Indy Hours"
    @event.mic_id = session[:user].id

    @event.max_attendees = 1

    @event.additional_service_hours = 0
    @event.additional_fundraisers = 0
    @event.additional_fellowships = 0
    @event.additional_leaderships = 0
    @event.additional_ceremonies = 0
    @event.additional_pledge_meetings = 0
    @event.additional_active_meetings = 0
    @event.additional_office_hours = 0

    @event.semester_index = Event.getSemesterValue(@event.date)

    if @event.save
      @record = AttendanceRecord.new
      @record.event_id = @event.id
      @record.member_id = session[:user].id
      @record.adjustment_hours = 0

      session[:user].up_to_date = false
      session[:user].save

      if @record.save
        redirect_to :action => "list"
      else
        render :action =>"indy_hour_submission", :error => "Unable to save event.  Please try again."
      end
    else
      render :action =>"indy_hour_submission", :error => "Unable to save event.  Please try again."
    end
  end


  def show
    @event = Event.find(params[:id])
    @attendees = AttendanceRecord.find(:all, :conditions => {:event_id => @event, :waitlist => 0}).size
    @drivers = AttendanceRecord.find(:all, :conditions => {:event_id => @event, :driver => 1, :waitlist => 0}).size

    Event.updateWaitList(@event)
  end

  def save
    if params[:id].nil?
      @event = Event.new
    else
      @event = Event.find(params[:id])

      AttendanceRecord.find(:all, :select => "attendance_records.member_id", :conditions => {:event_id => params[:id], :deleted => false}).each do |record|
        if(record.member_id != nil)
          member = Member.find(record.member_id)
          member.up_to_date = false
          member.save
        end
      end
    end

    @event.attributes = params[:event]

    if (params[:mic_id] == "")
      @event.mic_id = nil
    end

    @event.four_c = 0
    if !params[:c].nil?
      params[:c].each do |type|
        @event.four_c |= type.to_i
      end
    end

    if (@event.hours == nil)
      @event.hours = 0
    end
    if @event.additional_service_hours == nil
      @event.additional_service_hours = 0
    end
    if @event.additional_fundraisers == nil
      @event.additional_fundraisers = 0
    end
    if @event.additional_fellowships == nil
      @event.additional_fellowships = 0
    end
    if @event.additional_leaderships == nil
      @event.additional_leaderships = 0
    end
    if @event.additional_ceremonies == nil
      @event.additional_ceremonies = 0
    end
    if @event.additional_pledge_meetings == nil
      @event.additional_pledge_meetings = 0
    end
    if @event.additional_office_hours == nil
      @event.additional_office_hours = 0
    end

    @type = @event.event_type
    @hours = @event.hours
    if @hours == 0
      @hours = 1
    end

    if (@event.max_attendees == nil or @event.max_attendees > Member.find(:all).size)
      @event.max_attendees = Member.find(:all).size
    end

    if (@event.drivers == nil)
      @event.drivers = 0
    end

    @event.semester_index = Event.getSemesterValue(@event.date)

    if(@type == "Dues" or @type == "Dues (late)" or @type == "Committee")
      @event.approved = true
    end

    Event.updateWaitList(@event)

    if @event.save
      redirect_to :action => "show", :id => @event
    else
      render :action => "edit"
    end
  end


  def remove
    @event = Event.find(params[:id])
    AttendanceRecord.find(:all, :conditions => {:event_id => @event}).each do |record|
      record.deleted = true
      record.save
    end

    @event.deleted = true
    @event.save

    AttendanceRecord.find(:all, :select => "members.id", :conditions => ["attendance_records.event_id = #{@event.id}"], :include =>[:member]).each do |record|
      @member = Member.find(record.member.id)
      @member.up_to_date = false
      @member.save
    end

    if (params[:goto] != "old_list")
      redirect_to :action => "list"
    else
      redirect_to :action => "old_list"
    end
  end


  def edit
    @event = Event.find(params[:id])
  end


  def add_attendee
    @event = Event.find(params[:id])
    names = params[:member][:full_name].split(' ')

    #If member has a middle name, put it in the proper field.
    #If member has multiple middle names, we're fucked!
    if names.size == 3
      unless Member.find_by_first_name_and_last_name(names[0], names[1] + " " + names[2]).nil?
        @member = Member.find_by_first_name_and_last_name(names[0], names[1] + " " + names[2])
      else
        @member = Member.find_by_first_name_and_last_name(names[0] + " " + names[1], names[2])
      end
    else
      @member = Member.find_by_first_name_and_last_name(names[0], names[1])
    end

    if !@member.nil?
      if(AttendanceRecord.find(:all, :conditions => {:event_id => @event, :member_id => @member}).size == 0)

        @attendees = AttendanceRecord.find(:all, :conditions => {:event_id => @event, :waitlist => 0}).size
        @drivers = AttendanceRecord.find(:all, :conditions => {:event_id => @event, :driver => 1, :waitlist => 0}).size
        @attendance_record = AttendanceRecord.new
        @attendance_record.member = @member
        @attendance_record.event = @event
        @attendance_record.creator = session[:user]
        @attendance_record.adjustment_hours = 0.0
        if @event.event_type == "Committee"
          @attendance_record.attended = false
        end

        if params[:commit] == "Add as attendee"
          @attendance_record.driver = 0
          @attendance_record.waitlist = 0
        elsif params[:commit] == "Add to waitlist"
          @attendance_record.driver = 0
          @attendance_record.waitlist = 1
        elsif params[:commit] == "Add to waitlist as driver"
          @attendance_record.driver = 1
          @attendance_record.waitlist = 1
        elsif params[:commit] == "Add attendee"
          @attendance_record.driver = 0
          @attendance_record.waitlist = 0
        elsif params[:commit] == "Add as driver"
          @attendance_record.driver = 1
          @attendance_record.waitlist = 0
        else
          flash[:error] = "That button doesn't exist! Please contact the Internet Chair"
          render :action => "show", :id => @event
        end

        if Event.isBefore(Time.now, @event.date)
          if @attendance_record.waitlist == 0
            if @event.drivers > 0
              if @attendance_record.driver == false
                if @attendees - (@drivers > @event.drivers ? @event.drivers : @drivers) >= @event.max_attendees - @event.drivers
                  @attendance_record.waitlist = 1
                  flash[:error] = "Someone signed up right before you did! The member you added was put on the waitlist instead."
                end
              elsif @drivers >= @event.drivers
                if @attendees - (@drivers > @event.drivers ? @event.drivers : @drivers) < @event.max_attendees - @event.drivers
                  @attendance_record.driver = 0
                  flash[:error] = "Someone signed up to drive right before you did! The member you added doesn't need to drive to this event."
                else
                  @attendance_record.waitlist = 1
                  flash[:error] = "Someone signed up right before you did! The member you added was put on the waitlist instead."
                end
              end
            else
                if @attendees >= @event.max_attendees
                  @attendance_record.waitlist = 1
                  flash[:error] = "Someone signed up right before you did! The member you added was put on the waitlist instead."
                end
            end
          end
        end

        @attendance_record.save

        @member.up_to_date = false
        @member.save

      end
    else
      flash[:error] = "Member: #{params[:member][:full_name]} not found!"
    end

    redirect_to :action => "show", :id => @event
  end

  def mic_signup
    @event = Event.find(params[:event_id])
    @member = Member.find(params[:member_id])

    if (AttendanceRecord.find(:all, :conditions => {:member_id => "#{@member.id}", :event_id => "#{@event.id}", :waitlist => 0}).size == 0)
      flash[:error] = "Must be signed up for the event to MIC!"
    else
      @member.up_to_date = false
      @member.save

      @event.mic_id = @member.id
      @event.save
    end

    @attendees = AttendanceRecord.find(:all, :conditions => {:event_id => @event, :waitlist => 0}).size
    @drivers = AttendanceRecord.find(:all, :conditions => {:event_id => @event, :driver => 1, :waitlist => 0}).size
    render :action => "show", :id => @event
  end

  def mic_remove
    @event = Event.find(params[:event_id])
    @member = Member.find(params[:member_id])

    @event.mic_id = nil
    @event.save
    @member.up_to_date = false
    @member.save

    @attendees = AttendanceRecord.find(:all, :conditions => {:event_id => @event, :waitlist => 0}).size
    @drivers = AttendanceRecord.find(:all, :conditions => {:event_id => @event, :driver => 1, :waitlist => 0}).size
    render :action => "show", :id => @event
  end

  def un_approve_event
    @event = Event.find(params[:id])

    AttendanceRecord.find(:all, :select => "attendance_records.member_id", :conditions => {:event_id => params[:id], :deleted => false, :waitlist => 0}).each do |record|
      if(record.member_id != nil)
        member = Member.find(record.member_id)
        member.up_to_date = false
        member.save
      end
    end

    @event.approved = false
    @event.save

    if (params[:goto] == 'list')
      redirect_to :action => "list"
    elsif (params[:goto] == 'old_list')
      redirect_to :action => "old_list"
    else
      redirect_to :action => "show", :id => @event
    end
  end


  def approve_event
    AttendanceRecord.find(:all, :conditions => {:event_id => params[:id], :deleted => false, :waitlist => 1}).each do |record|
      record.destroy
    end

    @event = Event.find(params[:id])

    AttendanceRecord.find(:all, :select => "attendance_records.member_id", :conditions => {:event_id => params[:id], :deleted => false, :waitlist => 0}).each do |record|
      if(record.member_id != nil)
        member = Member.find(record.member_id)
        member.up_to_date = false
        member.save
      else
        record.destroy
      end
    end
    @event.approved = true
    @event.save

    if (params[:goto] == 'list')
      redirect_to :action => "list"
    elsif (params[:goto] == 'old_list')
      redirect_to :action => "old_list"
    else
      redirect_to :action => "show", :id => @event
    end
  end


  def add_current_user
    @event = Event.find(params[:id])
    @member = Member.find(params[:member_id])
    @attendees = AttendanceRecord.find(:all, :conditions => {:event_id => @event, :waitlist => 0}).size
    @drivers = AttendanceRecord.find(:all, :conditions => {:event_id => @event, :driver => 1, :waitlist => 0}).size

    if(AttendanceRecord.find(:all, :conditions => {:event_id => @event, :member_id => @member}).size == 0)

      @attendance_record = AttendanceRecord.new
      @attendance_record.member = @member
      @attendance_record.event = @event

      if params[:commit] == "Sign up for this event"
        @attendance_record.driver = 0
        @attendance_record.waitlist = 0
      elsif params[:commit] == "Sign up for the waitlist"
        @attendance_record.driver = 0
        @attendance_record.waitlist = 1
      elsif params[:commit] == "Sign up for the waitlist as driver"
        @attendance_record.driver = 1
        @attendance_record.waitlist = 1
      elsif params[:commit] == "Sign up as driver"
        @attendance_record.driver = 1
        @attendance_record.waitlist = 0
      else
        flash[:error] = "That button doesn't exist! Please contact the Internet Chair"
        render :action => "show", :id => @event
      end

      if Event.isBefore(Time.now, @event.date)
        if @attendance_record.waitlist == 0
          if @event.drivers > 0
            if @attendance_record.driver == false
              if @attendees - (@drivers > @event.drivers ? @event.drivers : @drivers) >= @event.max_attendees - @event.drivers
                @attendance_record.waitlist = 1
                flash[:error] = "Someone signed up right before you did! You were added to the waitlist instead."
              end
            elsif @drivers >= @event.drivers
              if @attendees - (@drivers > @event.drivers ? @event.drivers : @drivers) < @event.max_attendees - @event.drivers
                @attendance_record.driver = 0
                flash[:error] = "Someone signed up to drive right before you did! You don't need to drive to this event."
              else
                @attendance_record.waitlist = 1
                flash[:error] = "Someone signed up right before you did! You were added to the waitlist instead."
              end
            end
          else
              if @attendees >= @event.max_attendees
                @attendance_record.waitlist = 1
                flash[:error] = "Someone signed up right before you did! You were added to the waitlist instead."
              end
          end
        end
      end

      @attendance_record.creator = session[:user]
      @attendance_record.adjustment_hours = 0.0
      @attendance_record.save

      @member.up_to_date = false
      @member.save

    end

    redirect_to :action => "show", :id => @event
  end

  def update_attendees
    @event = Event.find(params[:event_id])

    if params[:commit] == "Remove selected"
      params[:selected].each do |member_id|
        attendance_record = AttendanceRecord.find_by_event_id_and_member_id(params[:event_id], member_id)

        member = Member.find(member_id)
        member.up_to_date = false
        member.save

        if @event.mic_id == member.id
          @event.mic_id = nil
          @event.save
        end

        attendance_record.destroy
      end
      Event.updateWaitList(@event)
    end

    if params[:commit] == "Did not show up" or params[:commit] == "Completed Requirements"
      params[:selected].each do |member_id|
        attendance_record = AttendanceRecord.find_by_event_id_and_member_id(params[:event_id], member_id)

        member = Member.find(member_id)
        member.up_to_date = false
        member.save

        attendance_record.attended = !attendance_record.attended
        attendance_record.save
      end
    end

    redirect_to :action => "show", :id => @event
  end

  def remove_attendee
    @event = Event.find(params[:event_id])
    attendance_record = AttendanceRecord.find_by_event_id_and_member_id(params[:event_id], params[:member_id])

    member = Member.find(attendance_record.member_id)
    member.up_to_date = false
    member.save

    if @event.mic_id == member.id
      @event.mic_id = nil
      @event.save
    end

    attendance_record.destroy

    Event.updateWaitList(@event)

    redirect_to :action => "show", :id => @event
  end

  def driver_false
    @event = Event.find(params[:event_id])
    @attendees = AttendanceRecord.find(:all, :conditions => {:event_id => @event, :waitlist => 0}).size
    @drivers = AttendanceRecord.find(:all, :conditions => {:event_id => @event, :driver => 1, :waitlist => 0}).size
    attendance_record = AttendanceRecord.find(:all, :conditions => {:id => params[:record_id]})[0]

    if ((@attendees - (@drivers > @event.drivers ? @event.drivers : @drivers) < @event.max_attendees - @event.drivers) or attendance_record.waitlist == 1) or (Event.isBefore(@event.date, Time.now))
      attendance_record.driver = false
      attendance_record.save

      member = Member.find(attendance_record.member_id)
      member.up_to_date = false
      member.save

      Event.updateWaitList(@event)
      @attendees = AttendanceRecord.find(:all, :conditions => {:event_id => @event, :waitlist => 0}).size
      @drivers = AttendanceRecord.find(:all, :conditions => {:event_id => @event, :driver => 1, :waitlist => 0}).size
    else
      flash[:error] = "Not enough spots to do that!"
    end

    render :action => "show", :id => @event
  end

  def driver_true
    @event = Event.find(params[:event_id])
    @attendees = AttendanceRecord.find(:all, :conditions => {:event_id => @event, :waitlist => 0}).size
    @drivers = AttendanceRecord.find(:all, :conditions => {:event_id => @event, :driver => 1, :waitlist => 0}).size
    attendance_record = AttendanceRecord.find(:all, :conditions => {:id => params[:record_id]})[0]

    if (@drivers < @event.drivers or @event.drivers == 0 or attendance_record.waitlist == 1) or (Event.isBefore(@event.date, Time.now))
      attendance_record.driver = true
      attendance_record.save

      member = Member.find(attendance_record.member_id)
      member.up_to_date = false
      member.save

      @event = Event.find(params[:event_id])
      Event.updateWaitList(@event)
      @attendees = AttendanceRecord.find(:all, :conditions => {:event_id => @event, :waitlist => 0}).size
      @drivers = AttendanceRecord.find(:all, :conditions => {:event_id => @event, :driver => 1, :waitlist => 0}).size
    else
      flash[:error] = "Already enough drivers!"
    end
    render :action => "show", :id => @event
  end

  def edit_attendee_hours
    @event = Event.find(params[:event_id])
    @member = Member.find(params[:member_id])
  end

  def submit_attendee_hours
    @event = Event.find(params[:event_id])
    attendance_record = AttendanceRecord.find_by_event_id_and_member_id(params[:event_id], params[:member_id])
    if (params[:adjustment_hours] != nil)
      attendance_record.adjustment_hours = params[:adjustment_hours]
      attendance_record.save

      member = Member.find(attendance_record.member_id)
      member.up_to_date = false
      member.save

    end
    redirect_to :action => "show", :id => @event
  end

  def show_replace
    @event = Event.find(params[:id])
    @attendees = AttendanceRecord.find_all_by_event_id(@event.id, :conditions => "waitlist = 0").sort { |a,b| a.member.last_name <=> b.member.last_name }
    render :update do |page|
      page.replace_html "tooltip", :partial => "replace_member", :locals => {:attendees => @attendees}
      page << "showTooltip(Element.cumulativeOffset($('replaceButton')))"
    end
  end

  def do_replace
    @event = Event.find(params[:id])

    if params[:member][:id] == "" or params[:attendance_record][:id] == ""
      flash[:error] = "Please choose someone to replace"
    elsif @event.attendance_records.find_by_member_id(params[:member][:id]).nil?
      attendance_record = AttendanceRecord.find(params[:attendance_record][:id])

      if @event.mic_id == attendance_record.member_id
        @event.mic_id = params[:member][:id]
        @event.save
      end

      attendance_record.member_id = params[:member][:id]
      attendance_record.save
    elsif @event.attendance_records.find_by_member_id(params[:member][:id]).waitlist == 1
      attendance_record = AttendanceRecord.find(params[:attendance_record][:id])
      old_attendance_record = @event.attendance_records.find_by_member_id(params[:member][:id])

      if @event.mic_id == attendance_record.member_id
        @event.mic_id = params[:member][:id]
        @event.save
      end

      attendance_record.member_id = params[:member][:id]
      attendance_record.save
      old_attendance_record.destroy
    else
      flash[:error] = "That member is already attending!"
    end

    redirect_to :action => "show", :id => @event
  end

end
